<?php
/*
 * IKPHP爱客网 安装程序 @copyright (c) 2012-3000 IKPHP All Rights Reserved @author 小麦
* @Email:810578553@qq.com
* @小麦 修改时间2014年3月19日晚 用户基础类
*/
namespace IKPHP\Common\Models;
use IKPHP\Api\UserApi;
use \Phalcon\Mvc\Model\Message;
use IKPHP\Common\Models\Setting;
use IKPHP\Common\Models\UserLevel;

class User extends BaseModel
{
	public $userid;
	public $username;
	
    public function getSource()
    {
        return IK."user";
    }
    public function initialize(){}
    /**
     * 登录指定用户
     * @param  integer $uid 用户ID
     * @return boolean      ture-登录成功，false-登录失败
     */
    public function login($uid){
        /* 检测是否在当前应用注册 */
        $user = $this->findFirst("userid='$uid'");
        if(!$user){ //未注册
            /* 在当前应用中注册用户 */
        	$Api = new UserApi();
        	$info = $Api->info($uid); 
        	if($info){
        		$user = new User();
        	    $user->userid = $uid;
        	    $user->username = $info[1];
        	    $user->email = $info[2];
        	    $user->reg_ip = $this->getDI()->getRequest()->getClientAddress();
        	    $user->reg_time = time();
        	    $user->roleid = 1;
        	    $user->count_score = 0;
        	    $user->count_follow = 0;
        	    $user->count_followed = 0;
        	    $user->status = 0;
        	    //注册成功
	            if(!$user->create()){
	            	$this->appendMessage(new Message("前台用户信息注册失败，请重试！"));
	                return false;
	            }        		
        	}else{
        		 $this->appendMessage(new Message("用户未激活或已禁用！")); //应用级别禁用
        		 return false;
        	}
        } elseif(0 != $user->status) {
            $this->appendMessage(new Message("用户未激活或已禁用！")); //应用级别禁用
            return false;
        }

        /* 登录用户 */
        $this->autoLogin($user);

        // 登陆完成钩子
        $tag_arg = array (
			'uid' => $uid,
			'uname' => $user->username,
			'action' => 'login',
			'actionname' => '登录'
		);
        hook('UserScore', 'changeScore', $tag_arg);

        return true;
    }
    /**
     * 自动登录用户
     * @param  integer $user 用户信息数组
     */
    private function autoLogin($user){
        /* 更新登录信息 */
    	$resuser = $this->findFirst($user->userid);
        if($resuser){
        	
        	$resuser->count_login = $resuser->count_login+1;
        	$resuser->last_login_time = time();
        	$resuser->last_login_ip = $this->getDI()->getRequest()->getClientAddress();
        	$resuser->save();
        	
        	$doname = empty($resuser->doname) ? $resuser->userid : $resuser->doname;
        	
        	/* 记录登录SESSION和COOKIES */
	        $auth = array(
	            'userid'             => $resuser->userid,
	            'username'        => $resuser->username,
	        	'email'        => $resuser->email,
				'doname'        => $doname,        
	            'last_login_time' => $resuser->last_login_time,
	        	'site_ck' => random(12),
	        );

			
	        $this->getDI()->get('session')->set('user_auth', $auth);
	        $this->getDI()->get('session')->set('user_auth_sign', data_auth_sign($auth));
	        //COOKIES

        	return true;
        	
        }else{
        	$this->appendMessage(new Message("自动登录用户失败！"));
        	return false;
        }
        
        return true;
    }
    /**
     * 注销当前用户
     * @return void
     */
    public function logout(){
        $this->getDI()->get('session')->remove('user_auth');
        $this->getDI()->get('session')->remove('user_auth_sign');
        return true;
    }
    /**
     * 获取字段信息
     * @param  integer $uid 用户ID
     * @param  array   $field 要获取的字段
     * @return result
     */ 
    public function getInfo($id, $field = array('*')){ 
    	$info = $this->findFirst(array('columns'=>$field, 'conditions'=>'userid = '.$id));
    	if(!$info){
    		return false;
    	}
    	return $info;
    }
    
    /*
     * 获取一个用户的信息
     * @param int $userid 用户ID
     * */
	public static function getOneUser($userid){
		$result = array();
        $cacheKey = 'user-'.$userid;
        $result = F($cacheKey,'','users'); 
        if(!$result){ 
			$strUser = self::findFirst("userid='$userid'"); 
			if($strUser == false){
				return false;
			}
			$strUser = $strUser->toArray();
			$strUser['face_48'] = avatar($userid, 48, $strUser['face']);
			$strUser['face_160'] = avatar($userid, 160, $strUser['face']);
			$strUser['face_240'] = avatar($userid, 240, $strUser['face']); 
			//地区
			if($strUser['areaid'] > 0){
				$areaMod = new Area();
				$strUser['area'] = $areaMod->getOneArea($strUser['areaid']);
			}else{
				$strUser['area'] = array(
					'areaid'	=> '0',
					'areaname' => '火星',
				);
			}
	
			//等级
			if($strUser['roleid']>0){
				$userLevel = new UserLevel();
				$arr_level = $userLevel->getLevelById($strUser['roleid']);
				$strUser['level'] =  $arr_level == false ? array('rolename'=>'无名号') : $arr_level;
			}else{
				$strUser['level'] = array('rolename'=>'无名号');
			}
			$strUser['count_follow'] = $strUser['count_follow'] ? $strUser['count_follow'] : 0;
			$strUser['count_followed'] = $strUser['count_followed'] ? $strUser['count_followed'] : 0; 
			//在线状态 下期开发
			//$time = time() - 15 * 60;
			//$isonline = M('user_online')->where(array('userid'=>$userid,'ctime'=>array('gt',$time)))->count();
			$strUser['isonline'] = 0 ;
			//个性域名
	        $strUser['doname'] = empty($strUser['doname']) ? $userid : $strUser['doname'];	
			//签名
			$pattern='/(http:\/\/|https:\/\/|ftp:\/\/)([\w:\/\.\?=&-_]+)/is';
	
			$strUser['signed'] = preg_replace($pattern, '<a rel="nofollow" target="_blank" href="\1\2">\1\2</a>', $strUser['signed']);
        	
			//缓存
			F($cacheKey, $strUser, 'users');
			$result = $strUser;
        }
		return $result;
	}
	//获取活跃会员
	public function getHotUser($limit){
		$where = array (
				'columns'=>'userid',
				'conditions'=>'status = 0',// 0 表示正常 1停用
				'order'=> 'last_login_time desc',
				'limit'=> $limit
		);
		$arrUserid = self::find($where);
		if($arrUserid){
			foreach($arrUserid->toArray() as $item){
				$result[] = $this->getOneUser($item['userid']);
			}
			return $result;		
		}
		return false;
	}
	//更新后执行
	public function afterSave(){
		$cacheKey = 'user-'.$this->userid;
		F($cacheKey,null,'users');
	} 

}
